package zhuyun.code.itemdecorationdemo

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import zhuyun.code.itemdecorationdemo.databinding.ItemRecyclerviewBinding

/**
 * @author: Administrator
 * @date: 2021/11/3
 */
class RecyclerAdapter(private val items:List<String>): RecyclerView.Adapter<RecyclerAdapter.BindingHolder<ItemRecyclerviewBinding>>(){


    override fun onCreateViewHolder(//创建viewholder
        parent: ViewGroup,
        viewType: Int
    ): BindingHolder<ItemRecyclerviewBinding> {
        val binding = DataBindingUtil.inflate<ItemRecyclerviewBinding>(LayoutInflater.from(parent.context),R.layout.item_recyclerview, parent, false)
        return BindingHolder<ItemRecyclerviewBinding>(binding)
    }

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: BindingHolder<ItemRecyclerviewBinding>, position: Int) {//实现数据与控件的绑定
        items[position].let { holder.bindData(it) }
    }

    class BindingHolder<T: ViewDataBinding>(private val viewBinding:T):RecyclerView.ViewHolder(viewBinding.root) {
        fun bindData(item: String){
            viewBinding.setVariable(BR.title, item)
        }
    }
}